#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QWebChannel"
#include "bridge.h"
#include "QPushButton"
#include <QWebEngineView>
#include <QWebChannel>
#include <QDir>
#include <QDebug>
#include <QEventLoop>
#include "bridge.h"
#include <QTimer>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_view = new QWebEngineView(this);
    m_channel = new QWebChannel(this);
    m_channel->registerObject("bridge", (QObject*)bridge::instance());
    m_view->page()->setWebChannel(m_channel);
    qDebug() << QString("file:///%1/%2").arg(QApplication::applicationDirPath()).arg("index.html");
    m_view->page()->load(QUrl(QString("file:///%1/%2").arg(QApplication::applicationDirPath()).arg("index.html")));

    m_view->show();

    connect(ui->pbAlert, &QPushButton::clicked, [this]() {
        m_view->page()->runJavaScript("showAlert()");
    });
}

MainWindow::~MainWindow()
{
    if (m_view)
        m_view->close();

    delete m_channel;
    delete m_view;
    delete ui;
}

void MainWindow::resizeEvent(QResizeEvent *)
{
    m_view->resize(this->size());
}

QVariant syncRunJavaScript(QWebEnginePage *page, const QString &javascript, int msec = 3000)
{
    QVariant result;
    QSharedPointer<QEventLoop> loop = QSharedPointer<QEventLoop>(new QEventLoop());
    QTimer::singleShot(msec, loop.data(), &QEventLoop::quit);
    page->runJavaScript(javascript, [loop, &result](const QVariant &val) {
        if (loop->isRunning()) {
            result = val;
            loop->quit();
        }
    });
    loop->exec();
    return result;
}

void MainWindow::slotGetWebWidth()
{
    QVariant result = syncRunJavaScript(m_view->page(), "getWindowWidth()");
    if (!result.isNull()) {
        qDebug() << result.toInt();
    }
}
